<template>
  <div id="modelMenuDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <div class="smallToolTitle">功能设定</div>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="qloading" @click="findModelMenuList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addModelMenuDialog()"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="modelMenuDelete"></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="tableBox">
      <vxe-table ref="modelMenuTableRef" :data="modelMenuList" :loading="qloading" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" :tree-config="{}" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="menuTitle" title="功能名称" width="150" tree-node align="left">
          <template #default="{ row }" >
                <el-link type="primary" :underline="false" @click="editModelMenuDialog(row)" v-if="isEmpty(row.parentId)">
                  <span>{{row.menuTitle}}</span>
                </el-link>
                <span v-else>{{row.menuTitle}}</span>
              </template>
        </vxe-column>
        
        <vxe-column field="staMenuCode" title="标准编号" width="100">
        </vxe-column>
        <vxe-column field="menuCode" title="功能编号" width="100">
        </vxe-column>

        <vxe-column field="url" title="路径" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left" width="120">
          <template #default="{ row }">
            <span>{{ row.url }}</span>
          </template>
        </vxe-column>
        <vxe-column field="icon" title="图标" width="50">
          <template #default="{ row }">
            <el-icon size="20" class="icon">
              <component :is="row.icon"></component>
            </el-icon>
          </template>
        </vxe-column>
        <vxe-column field="seq" title="顺序"> </vxe-column>

        <vxe-column title="操作" width="90" align="center" fixed="right">
          <template #default="{ row }">
            <!-- 新建子级按钮 -->
            <el-tooltip class="item" effect="dark" content="新建子菜单" placement="right" v-if="isEmpty(row.parentId)">
              <vxe-button type="text" status="primary" circle @click="addChildModelMenuDialog(row)">
                <el-icon>
                  <CirclePlus />
                </el-icon></vxe-button>
            </el-tooltip>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <vxe-modal v-model="isModelMenuVisiable" width="25vw" height="35vh" show-footer :mask="false" @close="cancelModelMenuEvent">
      <template #title>
        <span>菜单</span>
      </template>
      <template #default>
        <div class="form-panel">
          <vxe-form :data="modelMenuForm" title-width="80">
            <vxe-form-item title="标准编号" span="24" field="staMenuCode">
              <template #default="{ data }">
                <vxe-input v-model="data.staMenuCode" placeholder="标准编号"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="功能编号" span="24" field="menuCode">
              <template #default="{ data }">
                <vxe-input v-model="data.menuCode" placeholder="功能编号"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="功能名称" span="24" field="menuTitle">
              <template #default="{ data }">
                <vxe-input v-model="data.menuTitle" placeholder="功能名称"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="图标" span="24" field="icon">
              <template #default="{ data }">
                <vxe-input v-model="data.icon" placeholder="图标" @click="showSelectIocn" ref="reficon"></vxe-input>
                <SelectIcon ref="refselectIcon" @SelectIcon="selectIcon1"></SelectIcon>
              </template>
            </vxe-form-item>
            <vxe-form-item title="顺序" field="seq" span="24" :item-render="{}" title-overflow="title">
              <template #default="params">
                <vxe-input v-model="params.data.seq" type="number" min="0" max="1000" placeholder="顺序"></vxe-input>
              </template>
            </vxe-form-item>

          </vxe-form>
        </div>
      </template>
      <template #footer>
        <vxe-button type="text" class="button-white" @click="cancelModelMenuEvent">取消</vxe-button>
        <vxe-button type="text" class="button-blue" @click="confirmModelMenuEvent">确定</vxe-button>
      </template>
    </vxe-modal>

    <el-dialog title="功能字典" :show-close="false" v-model="showModuleMenuDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showModuleMenuDialog">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input style="width: 130px" v-model="searchModuleMenuForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findStaModuleMenuList2" @keyup="keyupModuleMenuEnter" @search-click="findStaMenuList2()"></vxe-input>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findStaModuleMenuList2"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="moduleMenuTableRef" :data="moduleMenuList" :loading="lloading" class="mytable-scrollbar dialogTable" border height="520px" align="center" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>
          <vxe-column type="checkbox" width="30" align="center"></vxe-column>
          <vxe-column field="icon" title="图标" width="50">
            <template #default="{ row }">
              <el-icon size="20" class="icon">
                <component :is="row.icon"></component>
              </el-icon>
            </template>
          </vxe-column>
          <vxe-column field="staMenuCode" title="标准编号" width="100">
          </vxe-column>
          <vxe-column field="menuCode" title="功能编号" width="100">
          </vxe-column>
          <vxe-column field="menuTitle" title="功能名称" width="100">
          </vxe-column>
          <vxe-column field="url" title="路径" align="left">
          </vxe-column>
          <vxe-column field="seq" title="顺序" width="100"> </vxe-column>
        </vxe-table>

        <div class="dialog-footer flex right justify-end">
          <el-button type="primary" @click="saveBacthModelMenu('moduleMenuTableRef')">确定</el-button>
          <el-button @click="closeModuleMenuDialog('moduleMenuTableRef')">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import SelectIcon from '@/components/SelectIcon.vue';

defineExpose({ initPage });
let refselectIcon = ref(null);

let disabledTag = ref(true); //中间质控品维护按钮标记
let qloading = ref(false); //右侧质控表格加载+刷新
let lloading = ref(false);
let isModelMenuVisiable = ref(false);

let staModelModule = ref(null);
let staModelMenu = ref(null);
let modelMenuList: any = reactive([]);

let modelMenuForm = reactive({
  id: null,
  modelId: '',
  modelCode: '',
  staModId: '',
  staModCode: '',
  staMenuId: '',
  staMenuCode: '',
  menuCode: '',
  menuTitle: '',
  icon: '',
  seq: 1,
  orgId: ''
});

function initPage(row: any) {
  if (isEmpty(row)) {
    staModelModule.value = {};
    modelMenuList.length = 0;
  } else {
    staModelModule.value = row;
    findModelMenuList();
  }
  if (!staModelModule.value.id) {
    disabledTag.value = true;
  } else {
    disabledTag.value = false;
  }
}
function findModelMenuList() {
  if (isEmpty(staModelModule.value)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    qloading.value = true;
    modelMenuList.length = 0; //放入数据前清空数据
    const url = '/lis/sta/staModelMenu/findModelMenuList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { modelId: staModelModule.value.modelId, staModId: staModelModule.value.staModId }
      })
      .then((res: any) => {
        modelMenuList.push(...res.data);
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}
function addModelMenuDialog() {
  modelMenuForm.modelId = staModelModule.value.modelId;
  modelMenuForm.modelCode = staModelModule.value.modelCode;
  modelMenuForm.staModId = staModelModule.value.staModId;
  modelMenuForm.staModCode = staModelModule.value.staModCode;
  isModelMenuVisiable.value = true;
}
function editModelMenuDialog(row: any) {
  setModelMenuForm(row);
  isModelMenuVisiable.value = true;
}

function cancelModelMenuEvent() {
  clearModelMenuForm();
  isModelMenuVisiable.value = false;
}

function confirmModelMenuEvent() {
  if (modelMenuForm.id === null) {
    const url = '/lis/sta/staModelMenu/addModelMenu';
    const staModel = {
      modelId: modelMenuForm.modelId,
      modelCode: modelMenuForm.modelCode,
      staModId: modelMenuForm.staModId,
      staModCode: modelMenuForm.staModCode,
      staMenuId: modelMenuForm.staMenuId,
      staMenuCode: modelMenuForm.staMenuCode,
      menuCode: modelMenuForm.menuCode,
      menuTitle: modelMenuForm.menuTitle,
      icon: modelMenuForm.icon,
      seq: modelMenuForm.seq
    };
    proxy.$http
      .post(url, staModel)
      .then((res: any) => {
        VxeMessage('新增成功', VxeNotifyType.success);
        clearModelMenuForm();
        // sltStaModel.value.id = res.data.id;
        findModelMenuList();
        isModelMenuVisiable.value = false;
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/lis/sta/staModelMenu/editModelMenu';
    const staModel = {
      id: modelMenuForm.id,
      modelId: modelMenuForm.modelId,
      modelCode: modelMenuForm.modelCode,
      staModId: modelMenuForm.staModId,
      staModCode: modelMenuForm.staModCode,
      staMenuId: modelMenuForm.staMenuId,
      staMenuCode: modelMenuForm.staMenuCode,
      menuCode: modelMenuForm.menuCode,
      menuTitle: modelMenuForm.menuTitle,
      icon: modelMenuForm.icon,
      seq: modelMenuForm.seq
    };
    proxy.$http
      .post(url, staModel)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        // sltStaModel.value.id = res.data.id;
        findModelMenuList();
        clearModelMenuForm();
        isModelMenuVisiable.value = false;
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

// 清空中间规则弹框表单
function clearModelMenuForm() {
  modelMenuForm.id = null;
  modelMenuForm.modelId = '';
  modelMenuForm.modelCode = '';
  modelMenuForm.staModId = '';
  modelMenuForm.staModCode = '';
  modelMenuForm.staMenuId = '';
  modelMenuForm.staMenuCode = '';
  modelMenuForm.menuCode = '';
  modelMenuForm.menuTitle = '';
  modelMenuForm.icon = '';
  modelMenuForm.seq = 1;
  modelMenuForm.orgId = '';
}

// 编辑当前行规则
function setModelMenuForm(row: any) {
  modelMenuForm.id = row.id;
  modelMenuForm.modelId = row.modelId;
  modelMenuForm.modelCode = row.modelCode;
  modelMenuForm.staModId = row.staModId;
  modelMenuForm.staModCode = row.staModCode;
  modelMenuForm.staMenuId = row.staMenuId;
  modelMenuForm.staMenuCode = row.staMenuCode;
  modelMenuForm.menuCode = row.menuCode;
  modelMenuForm.menuTitle = row.menuTitle;
  modelMenuForm.icon = row.icon;
  modelMenuForm.seq = row.seq;
  modelMenuForm.orgId = row.orgId;
}

function modelMenuDelete() {
  const sltModelMenus = (proxy.$refs.modelMenuTableRef as any).getCheckboxRecords();
  if (!(sltModelMenus.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { staModelMenuList: sltModelMenus };
        const url = '/lis/sta/staModelMenu/batchDeleteModelMenuList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findModelMenuList();
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

let showModuleMenuDialog = ref(false);
let searchModuleMenuForm = reactive({
  seachValue: ''
});
let moduleMenuList: any = reactive([]);

async function addChildModelMenuDialog(row: any) {
  (proxy.$refs.modelMenuTableRef as any).setAllRowExpand(true);
  if (isEmpty(row)) {
    staModelMenu.value = {};
    VxeMessage('请选择模块', VxeNotifyType.error);
  } else {
    await (proxy.$refs.modelMenuTableRef as any).setTreeExpand(row, true); //新建一行空数据时展开这一栏

    staModelMenu.value = row;
    findStaModuleMenuList(row);
    showModuleMenuDialog.value = true;
  }
}

// 弹框取消按钮
function closeModuleMenuDialog() {
  searchModuleMenuForm.seachValue = '';
  showModuleMenuDialog.value = false;
}
function findStaModuleMenuList(row: any) {
  if (isEmpty(row)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    lloading.value = true;
    moduleMenuList.length = 0; //放入数据前清空数据
    const url = '/lis/sta/staModuleMenu/findStaModuleMenuList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { staModId: row.staModId }
      })
      .then((res: any) => {
        moduleMenuList.push(...res.data);
        lloading.value = false;
      })
      .catch((err: any) => {
        lloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

function findStaModuleMenuList2() {
  if (isEmpty(staModelMenu.value)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    lloading.value = true;
    moduleMenuList.length = 0; //放入数据前清空数据
    const url = '/lis/sta/staModuleMenu/findStaModuleMenuList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { seachValue: searchModuleMenuForm.seachValue, staModId: staModelMenu.value.staModId }
      })
      .then((res: any) => {
        moduleMenuList.push(...res.data);
        const staMenuIds = staModelMenu.value.children.map((m) => m.staMenuId);
        const ilist = moduleMenuList.filter((p: any) => staMenuIds.includes(p.staMenuId));
        const $table = proxy.$refs.moduleMenuTableRef;
        $table.setCheckboxRow(ilist, true);
        lloading.value = false;
      })
      .catch((err: any) => {
        lloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

function saveBacthModelMenu() {
  const selectRows = (proxy.$refs.moduleMenuTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addModelMenuList = [];
    for (const sltRow of selectRows) {
      const modelMenu = staModelMenu.value.children.find((qc: any) => qc.staMenuId == sltRow.staMenuId);
      if (isEmpty(modelMenu)) {
        const addModelMenu = {
          modelId: staModelMenu.value.modelId,
          modelCode: staModelMenu.value.modelCode,
          staModId: staModelMenu.value.staModId,
          staModCode: staModelMenu.value.staModCode,
          staMenuId: sltRow.staMenuId,
          staMenuCode: sltRow.staMenuCode,
          parentId: staModelMenu.value.id,
          menuCode: sltRow.menuCode,
          menuTitle: sltRow.menuTitle,
          icon: sltRow.icon,
          seq: sltRow.seq
        };
        addModelMenuList.push(addModelMenu);
      }
    }
    if (addModelMenuList.length > 0) {
      const data = { staModelMenuList: addModelMenuList };
      const url = '/lis/sta/staModelMenu/batchAddModelMenuList';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          findModelMenuList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
  closeModuleMenuDialog();
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = staModelMenu.value.children.filter((p: any) => {
    const kn = moduleMenuList.find((k) => k.staMenuId == p.staMenuId);
    defaultSelecteRowKeys.push(kn.id);
    return p.staMenuId == row.staMenuId;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = staModelMenu.value.children.filter((p: any) => {});
  return obj.length == 0;
}

function keyupModuleMenuEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findStaModuleMenuList2();
  }
}

function selectIcon1(icon: any) {
  modelMenuForm.icon = icon;
  setTimeout(() => {
    proxy.$refs.reficon.blur();
  }, 100);
}
function showSelectIocn() {
  refselectIcon.value.initPage(true);
}
</script>

<style lang="scss" scoped>
#modelMenuDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>